<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import axios from 'axios'

const route = useRoute()
const router = useRouter()

// 帖子数据
const post = ref<any>({})
// 评论数据
const comments = ref<any[]>([])
// 新评论内容
const newComment = ref('')
// 加载状态
const loading = ref(false)
// 评论加载状态
const commentLoading = ref(false)
// 控制评论折叠状态
const expandedComments = ref<Set<number>>(new Set())

// 获取帖子详情
const fetchPostDetail = async () => {
  try {
    const postId = route.query.postId
    if (!postId) {
      showToast('帖子ID不存在')
      return
    }

    loading.value = true
    const token = sessionStorage.getItem("token")

    const config: any = {}
    if (token) {
      config.headers = { 'token': token }
    }

    // 使用 /api/post/get 接口获取帖子详情和评论
    const response = await axios.get(`/api/post/get`, {
      ...config,
      params: {
        postId: postId
      }
    })

    if (response.data.code === 200) {
      post.value = response.data.data
      console.log('Post data:', post.value); // 调试信息

      // 确保 commentList 存在
      const commentList = post.value.commentList || []
      console.log('Comment list:', commentList); // 调试信息

      // 处理评论层级关系
      processComments(commentList)

      // 默认展开所有评论的回复
      comments.value.forEach(comment => {
        if (comment.replies && comment.replies.length > 0) {
          expandedComments.value.add(comment.commentId);
        }
      });

      // 处理用户信息
      if (!post.value.users) {
        // 从后端返回的数据中获取用户信息
        const userId = post.value.userId || 0
        // 这里我们可能需要额外获取用户信息，因为后端的get方法可能没有像page方法那样处理用户信息
        try {
          const userResponse = await axios.get(`/api/users/getById`, {
            ...config,
            data: userId
          })
          if (userResponse.data.code === 200) {
            post.value.users = userResponse.data.data
          }
        } catch (userError) {
          // 如果获取用户信息失败，使用默认值
          post.value.users = {
            userId: userId,
            nickname: '匿名用户',
            avatar: '',
            gender: '未知',
            height: 0,
            targetWeight: 0
          }
        }
      }
    } else {
      showToast(response.data.msg || '获取帖子详情失败')
    }
  } catch (error) {
    showToast('网络错误')
    console.error('Error fetching post detail:', error)
  } finally {
    loading.value = false
  }
}

// 处理评论层级关系
const processComments = (allComments: any[]) => {
  console.log('All comments:', allComments); // 调试信息

  // 先确保每条评论都有 users 对象
  allComments.forEach(comment => {
    if (!comment.users) {
      comment.users = {
        nickname: '匿名用户',
        avatar: 'https://img.yzcdn.cn/vant/cat.jpeg'
      };
    }
  });

  // 创建评论映射，便于查找
  const commentMap = new Map();
  allComments.forEach((comment: any) => {
    comment.replies = []; // 初始化 replies 数组
    // 使用深拷贝确保响应式更新
    const commentCopy = JSON.parse(JSON.stringify(comment));
    commentCopy.replies = [];
    commentMap.set(comment.commentId, commentCopy);
  });

  // 分离顶级评论和回复
  const topLevelComments = [];
  const replies = [];

  allComments.forEach((comment: any) => {
    // 放宽判断条件，更灵活地识别顶级评论
    if (!comment.upUserId || comment.upUserId === null || comment.upUserId === undefined || 
        comment.upUserId === "" || comment.upUserId === 0 || comment.upUserId === "0") {
      // 顶级评论
      topLevelComments.push(JSON.parse(JSON.stringify(comment)));
    } else {
      // 回复
      replies.push(JSON.parse(JSON.stringify(comment)));
    }
  });

  console.log('Top level comments:', topLevelComments); // 调试信息
  console.log('Replies:', replies); // 调试信息

  // 重新构建评论映射（基于拷贝后的顶级评论）
  const newCommentMap = new Map();
  topLevelComments.forEach((comment: any) => {
    comment.replies = []; // 确保 replies 数组存在
    newCommentMap.set(comment.commentId, comment);
  });

  // 将回复关联到对应的顶级评论
  replies.forEach((reply: any) => {
    // 查找父评论（处理数字和字符串类型）
    const parentId = typeof reply.upUserId === 'string' ? parseInt(reply.upUserId) : reply.upUserId;
    console.log('Reply:', reply); // 调试信息
    console.log('Parent ID:', parentId); // 调试信息
    const parentComment = newCommentMap.get(parentId);
    console.log('Parent comment:', parentComment); // 调试信息
    if (parentComment) {
      // 确保 replies 数组存在
      if (!parentComment.replies) {
        parentComment.replies = [];
      }
      parentComment.replies.push(reply);
      console.log('Added reply to parent comment'); // 调试信息
    } else {
      // 如果找不到父评论，作为顶级评论处理
      topLevelComments.push(reply);
      console.log('Moved reply to top level comments'); // 调试信息
    }
  });

  // 按时间排序顶级评论和回复
  topLevelComments.sort((a, b) => new Date(b.commentTime).getTime() - new Date(a.commentTime).getTime());
  topLevelComments.forEach(comment => {
    if (comment.replies && comment.replies.length > 0) {
      comment.replies.sort((a, b) => new Date(a.commentTime).getTime() - new Date(b.commentTime).getTime());
      // 默认展开所有回复
      expandedComments.value.add(comment.commentId);
    }
  });

  comments.value = topLevelComments;
  console.log('Final comments with replies:', topLevelComments); // 调试信息
  console.log('First comment replies:', topLevelComments[0]?.replies); // 调试信息
  console.log('Second comment replies:', topLevelComments[1]?.replies); // 调试信息
}

// 获取评论列表（不再需要单独获取）
const fetchComments = async () => {
  // 评论数据已经包含在帖子详情中，不需要单独获取
  return;
}

// 发布评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    showToast('请输入评论内容')
    return
  }

  try {
    const token = sessionStorage.getItem("token")
    if (!token) {
      showToast('请先登录')
      return
    }

    const postId = route.query.postId
    if (!postId) {
      showToast('帖子ID不存在')
      return
    }
    //准备请求数据
    let requestData: any = {
      postId: postId,
      content: newComment.value,
      // 对于帖子评论，不设置 upUserId 或设置为 null
      upUserId: null
    }
    // 检查是否是回复特定评论
    const replyMatch = newComment.value.match(/^@([^ ]+)/);
    if (replyMatch) {
      // 查找被回复的用户
      const repliedUser = replyMatch[1];
      // 在现有评论中查找被回复的评论
      const allComments = [...comments.value];
      comments.value.forEach(comment => {
        if (comment.replies) {
          allComments.push(...comment.replies);
        }
      });

      const targetComment = allComments.find(comment =>
          comment.users && comment.users.nickname === repliedUser
      );

      if (targetComment) {
        // 设置被回复的评论ID
        requestData.upUserId = targetComment.commentId;
      }
    }

    // 使用/comment/addReply接口
    const response = await axios.post('/api/comment/addReply', requestData, {
      headers: {
        'token': token
      }
    })

    if (response.data.code === 200) {
      showToast('评论成功')
      newComment.value = ''
      // 重新获取帖子详情（包括评论）
      fetchPostDetail()
    } else {
      showToast(response.data.msg || '评论失败')
    }
  } catch (error) {
    showToast('网络错误')
    console.error('Error submitting comment:', error)
  }
}

// 格式化时间显示
const formatTime = (timeString: string) => {
  if (!timeString) return ''

  const date = new Date(timeString)
  if (isNaN(date.getTime())) return ''

  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / (1000 * 60))

  if (minutes < 1) {
    return '刚刚'
  } else if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (minutes < 24 * 60) {
    const hours = Math.floor(minutes / 60)
    return `${hours}小时前`
  } else {
    const days = Math.floor(minutes / (24 * 60))
    return `${days}天前`
  }
}

// 点赞功能
const handleLike = async () => {
  try {
    const token = sessionStorage.getItem("token")
    if (!token) {
      showToast('请先登录')
      return
    }

    const postId = post.value.postId
    if (!postId) return

    const response = await axios.get('/api/post/likes', {
      params: {
        postId: postId
      },
      headers: {
        'token': token
      }
    })

    if (response.data.code === 200) {
      // 更新点赞状态和数量
      post.value.likes = response.data.data.likes
      post.value.userLiked = response.data.data.isLiked
      showToast(response.data.msg)
    } else {
      showToast(response.data.msg || '操作失败')
    }
  } catch (error) {
    showToast('网络错误')
    console.error('Error liking post:', error)
  }
}

// 点赞评论
const handleCommentLike = async (comment: any) => {
  try {
    const token = sessionStorage.getItem("token")
    if (!token) {
      showToast('请先登录')
      return
    }

    const response = await axios.get('/api/comment/likes', {
      params: {
        commentId: comment.commentId
      },
      headers: {
        'token': token
      }
    })

    if (response.data.code === 200) {
      // 更新评论点赞状态和数量
      comment.likes = response.data.data.likes
      comment.userLiked = response.data.data.isLiked
      showToast(response.data.msg)
    } else {
      showToast(response.data.msg || '操作失败')
    }
  } catch (error) {
    showToast('网络错误')
    console.error('Error liking comment:', error)
  }
}

// 切换评论展开/折叠状态
const toggleCommentExpansion = (commentId: number) => {
  if (expandedComments.value.has(commentId)) {
    expandedComments.value.delete(commentId)
  } else {
    expandedComments.value.add(commentId)
  }
}

// 回复特定评论
const replyToComment = (comment: any) => {
  // 在输入框中添加"@用户名"前缀
  newComment.value = `@${comment.users?.nickname || '匿名用户'} `;
}

// 获取回复目标用户
const getReplyTargetUser = (reply: any, parentComment: any) => {
  // 如果是直接回复顶级评论，则目标用户是顶级评论的作者
  if (reply.upUserId === parentComment.commentId) {
    return parentComment.users?.nickname || '匿名用户';
  }
  
  // 如果是回复其他回复，则需要查找目标回复
  if (parentComment.replies) {
    const targetReply = parentComment.replies.find((r: any) => r.commentId === reply.upUserId);
    if (targetReply) {
      return targetReply.users?.nickname || '匿名用户';
    }
  }
  
  // 默认返回父级评论作者
  return parentComment.users?.nickname || '匿名用户';
}

// 关注功能
const handleFollow = async () => {
  try {
    const token = sessionStorage.getItem("token")
    if (!token) {
      showToast('请先登录')
      return
    }

    // 获取当前用户ID和被关注用户ID
    const currentUserId = sessionStorage.getItem("userId")
    const followId = post.value.userId

    if (!currentUserId || !followId) {
      showToast('无法获取用户信息')
      return
    }

    // 调用关注接口
    const response = await axios.post('/api/userFollow/add', {
      userId: currentUserId,
      followId: followId
    }, {
      headers: {
        'token': token
      }
    })

    if (response.data.code === 200) {
      // 更新关注状态
      post.value.userFollowed = true
      showToast(response.data.msg)
    } else {
      showToast(response.data.msg || '操作失败')
    }
  } catch (error) {
    showToast('网络错误')
    console.error('Error following user:', error)
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

onMounted(() => {
  fetchPostDetail()
})
</script>

<template>
  <div class="comment-detail-container">
    <van-nav-bar
      title="帖子详情"
      left-text="返回"
      left-arrow
      @click-left="goBack"
    />

    <van-loading v-if="loading" class="loading" vertical>加载中...</van-loading>

    <div v-else class="content">
      <!-- 帖子内容 -->
      <div class="post-detail">
        <div class="post-header">
          <van-image
            :src="post.users?.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'"
            round
            width="40"
            height="40"
            class="user-avatar"
          />
          <div class="user-info">
            <div class="user-name">{{ post.users?.nickname || '匿名用户' }}</div>
            <div class="post-time">{{ formatTime(post.postTime) }}</div>
          </div>
          <van-button
            v-if="!post.userFollowed"
            size="small"
            type="primary"
            class="follow-button"
            @click="handleFollow"
          >
            关注
          </van-button>
          <van-button
            v-else
            size="small"
            class="follow-button followed"
            @click="handleFollow"
          >
            已关注
          </van-button>
        </div>

        <div class="post-content">
          {{ post.content || '' }}
        </div>

        <!-- 图片展示 -->
        <div v-if="post.images" class="post-images">
          <div
            v-for="(image, index) in post.images.split(',')"
            :key="index"
            class="image-container"
          >
            <van-image
              :src="image.trim()"
              width="100%"
              :height="200"
              fit="cover"
              radius="8"
            />
          </div>
        </div>

        <!-- 点赞 -->
        <div class="post-actions">
          <div class="like-section" @click="handleLike">
            <van-icon
              :name="post.userLiked ? 'like' : 'like-o'"
              :color="post.userLiked ? '#1989fa' : '#ccc'"
              size="18"
            />
            <span :class="{ liked: post.userLiked }">{{ post.likes || 0 }}</span>
          </div>
        </div>
      </div>

      <!-- 评论区域 -->
      <div class="comments-section">
        <!-- 使用后端返回的评论数量 -->
        <div class="section-title">评论 ({{ post.commentCount || comments.length }})</div>

        <van-loading v-if="loading" class="comments-loading" vertical>加载评论中...</van-loading>

        <div v-else class="comments-list">
          <div v-for="comment in comments" :key="comment.commentId" class="comment-item">
            <van-image
              :src="comment.users?.avatar || 'https://img.yzcdn.cn/vant/cat.jpeg'"
              round
              width="32"
              height="32"
              class="comment-avatar"
            />
            <div class="comment-content">
              <div class="comment-user">{{ comment.users?.nickname || '匿名用户' }}</div>
              <div class="comment-text">{{ comment.content }}</div>
              <div class="comment-time">{{ formatTime(comment.commentTime) }}</div>

              <!-- 评论操作 -->
              <div class="comment-actions">
                <div class="comment-like" @click="handleCommentLike(comment)">
                  <van-icon
                    :name="comment.userLiked ? 'like' : 'like-o'"
                    :color="comment.userLiked ? '#1989fa' : '#999'"
                    size="16"
                  />
                  <span :class="{ liked: comment.userLiked }">{{ comment.likes || 0 }}</span>
                </div>
                <div class="comment-reply" @click="replyToComment(comment)">
                  <van-icon name="comment-o" size="16" color="#999" />
                  <span>回复</span>
                </div>
              </div>

              <!-- 显示二级评论（回复） -->
              <div v-if="comment.replies && comment.replies.length > 0" class="reply-section">
                <div class="reply-toggle" @click="toggleCommentExpansion(comment.commentId)">
                  {{ expandedComments.has(comment.commentId) ? '收起回复' : `展开${comment.replies.length}条回复` }}
                  <van-icon
                    :name="expandedComments.has(comment.commentId) ? 'arrow-up' : 'arrow-down'"
                    size="14"
                  />
                </div>

                <div v-show="true" class="reply-list">
                  <div v-for="reply in comment.replies" :key="reply.commentId" class="reply-item">
                    <div class="reply-content">
                      <span class="reply-user">{{ reply.users?.nickname || '匿名用户' }}</span>
                      <span class="reply-action-text">回复</span>
                      <span class="reply-target-user">
                        {{ getReplyTargetUser(reply, comment) }}
                      </span>
                      <span class="reply-text">: {{ reply.content }}</span>
                    </div>
                    <div class="reply-info">
                      <div class="reply-time">{{ formatTime(reply.commentTime) }}</div>
                      <div class="reply-like" @click="handleCommentLike(reply)">
                        <van-icon
                          :name="reply.userLiked ? 'like' : 'like-o'"
                          :color="reply.userLiked ? '#1989fa' : '#999'"
                          size="14"
                        />
                        <span :class="{ liked: reply.userLiked }">{{ reply.likes || 0 }}</span>
                      </div>
                      <div class="reply-action" @click="replyToComment(reply)">
                        <van-icon name="comment-o" size="14" color="#999" />
                      </div>
                    </div>
                  </div>
                </div>
                <div v-if="!comment.replies || comment.replies.length === 0">
                  没有回复内容 (replies: {{ comment.replies ? comment.replies.length : 'undefined' }})
                </div>
              </div>
              <div v-else>
                没有回复区域 (replies: {{ comment.replies ? comment.replies.length : 'undefined' }})
              </div>
            </div>
          </div>

          <div v-if="comments.length === 0" class="no-comments">
            暂无评论，快来抢沙发吧！
          </div>
        </div>
      </div>
    </div>

    <!-- 评论输入框 -->
    <div class="comment-input-area">
      <van-field
        v-model="newComment"
        placeholder="请输入评论内容"
        type="textarea"
        autosize
        rows="1"
      >
        <template #button>
          <van-button size="small" type="primary" @click="submitComment">发送</van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<style scoped>
.comment-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 70px; /* 增加底部内边距，为输入区域留出空间 */
}

.loading {
  text-align: center;
  padding: 20px;
}

.content {
  padding: 16px;
}

.post-detail {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.user-avatar {
  margin-right: 12px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.follow-button {
  height: 30px;
}

.follow-button.followed {
  background-color: #f5f5f5;
  border-color: #ddd;
  color: #999;
}

.post-content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  margin-bottom: 12px;
  white-space: pre-wrap;
}

.post-images {
  display: grid;
  grid-template-columns: 1fr;
  gap: 8px;
  margin-bottom: 12px;
}

.image-container {
  width: 100%;
  height: 200px;
}

@media (min-width: 480px) {
  .post-images {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (min-width: 768px) {
  .post-images {
    grid-template-columns: repeat(3, 1fr);
  }
}

.post-actions {
  display: flex;
  justify-content: flex-end;
}

.like-section {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.like-section span {
  margin-left: 5px;
  font-size: 14px;
  color: #999;
}

.like-section .liked {
  color: #1989fa;
}

.comments-section {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
}

.comments-loading {
  text-align: center;
  padding: 10px;
}

.comment-item {
  display: flex;
  margin-bottom: 16px;
}

.comment-avatar {
  margin-right: 12px;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-user {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.comment-text {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
  line-height: 1.4;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-actions {
  display: flex;
  gap: 16px;
  margin-top: 6px;
}

.comment-like,
.comment-reply {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
  cursor: pointer;
}

.comment-like span,
.comment-reply span {
  margin-left: 4px;
}

.comment-like .liked {
  color: #1989fa;
}

/* 回复区域样式 */
.reply-section {
  margin-top: 10px;
}

.reply-toggle {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #1989fa;
  cursor: pointer;
  padding: 6px 0;
}

.reply-list {
  padding-left: 10px;
  border-left: 2px solid #f0f0f0;
}

.reply-item {
  margin-bottom: 8px;
  padding: 8px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.reply-content {
  font-size: 13px;
  margin-bottom: 4px;
  line-height: 1.4;
}

.reply-user {
  font-weight: 500;
  color: #1989fa;
  margin-right: 5px;
}

.reply-action-text {
  color: #999;
  margin-right: 5px;
}

.reply-target-user {
  font-weight: 500;
  color: #1989fa;
  margin-right: 5px;
}

.reply-text {
  color: #666;
}

.reply-info {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.reply-time {
  flex: 1;
}

.reply-like {
  display: flex;
  align-items: center;
  margin-right: 10px;
  cursor: pointer;
}

.reply-like span {
  margin-left: 3px;
}

.reply-like .liked {
  color: #1989fa;
}

.reply-action {
  cursor: pointer;
}

.no-comments {
  text-align: center;
  color: #999;
  padding: 20px 0;
}

.comment-input-area {
  position: fixed;
  bottom: 50px; /* 增加底部间距，避免被导航栏遮挡 */
  left: 0;
  right: 0;
  background: #fff;
  padding: 10px 16px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
}
</style>